/* BEGIN LICENSE
 * Copyright (C) 2015 Fedja Beader <fedja@protonmail.ch>
 * Copyright (C) 2008-2014 Stewart Smith <stewart@flamingspork.com>
 * This program is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License version 3, as published 
 * by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranties of 
 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
 * PURPOSE.  See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 * END LICENSE */

#include "config.h"
#include "libcachesave/visibility.h"

#undef _FILE_OFFSET_BITS // Hack to get open and open64 on 32bit
#undef __USE_FILE_OFFSET64
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <stdarg.h>
#include <pthread.h>
#include <stdio.h>

typedef ssize_t (*libc_read_t)(int, void*, size_t);

static libc_read_t libc_read= NULL;

#define ASSIGN_DLSYM_OR_DIE(name)			\
        libc_##name = (libc_##name##_##t)(intptr_t)dlsym(RTLD_NEXT, #name);			\
        if (!libc_##name || dlerror())				\
                _exit(1);

#define ASSIGN_DLSYM_IF_EXIST(name)			\
        libc_##name = (libc_##name##_##t)(intptr_t)dlsym(RTLD_NEXT, #name);			\
						   dlerror();


void __attribute__ ((constructor)) cachesave_init(void);

void __attribute__ ((constructor)) cachesave_init(void)
{
	ASSIGN_DLSYM_OR_DIE(read);
}

ssize_t LIBEATMYDATA_API read(int fd, void *buf, size_t count)
{
	posix_fadvise (fd, 0, 0, POSIX_FADV_DONTNEED);
	posix_fadvise (fd, 0, 0, POSIX_FADV_NOREUSE);

	return (*libc_read)(fd, buf, count);
}
